package com.zige.zige.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;


public class ImageHelper {

	public static Bitmap getPic(Context context, String path) {
		byte[] bitmapArr = decodeBitmap(path);
		if(bitmapArr == null)
			return null;
			
		Bitmap bitmapOrg = BitmapFactory.decodeByteArray(bitmapArr, 0, bitmapArr.length);
		Bitmap resizedBitmap = scaleBitmap(bitmapOrg);
		return resizedBitmap;
	}

	public static Bitmap getPic(Context context, String path, Options op) {
		Bitmap bitmapOrg = BitmapFactory.decodeByteArray(decodeBitmap(path), 0,
				decodeBitmap(path).length, op);
		Bitmap resizedBitmap = scaleBitmap(bitmapOrg);
		return resizedBitmap;
	}

	private static int[] calWH(int ow, int oh) {
		int[] w_h = new int[2];
		int scaled = ow> oh? oh/ 220 : ow / 220;
		w_h[0] = ow / scaled;
		w_h[1] = oh / scaled;
		return w_h;
	}

	public static Bitmap scaleBitmap(Bitmap bitmapOrg) {
		if (null == bitmapOrg)
			return null;
		// 获取这个图片的宽和高
		int width = bitmapOrg.getWidth();
		int height = bitmapOrg.getHeight();

		// 定义预转换成的图片的宽度和高度
		int newWidth = 0;
		int newHeight = 0;
		if (width < height) {
			int[] w_h = calWH(width, height);
			newWidth = w_h[0];
			newHeight = w_h[1];
		}else{
			int[] w_h = calWH(height, width);
			newWidth = w_h[1];
			newHeight = w_h[0];
		}

		// 计算缩放率，新尺寸除原始尺寸
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();

		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);

		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width,
				height, matrix, true);
		return resizedBitmap;
	}

	public static Bitmap addWaterMark(Bitmap paramBitmap, String paramString1,
			String paramString2, String paramString3, String paramString4) {
		if ((paramBitmap == null) || (paramString2 == null)
				|| (paramString1 == null) || (paramString3 == null)) {
			LogUtils.e("VisitShopPhotoDetail",
					"addWaterMark--  src == null ||  text == null");
			return paramBitmap;
		}
		int i = paramBitmap.getWidth();
		int j = paramBitmap.getHeight();
		Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.ARGB_8888);
		Canvas localCanvas = new Canvas(localBitmap);
		Paint localPaint = new Paint();
		localPaint.setColor(-1);
		localPaint.setTextSize(18.0F);
		localPaint.setColor(-1);
		localPaint.setFakeBoldText(true);
		localPaint.setAntiAlias(true);
		localPaint.setDither(true);
		float f;
		f = i - 310;
		// if (i < 350) {
		// localPaint.setTextSize(13.0F);
		// f = 0.0F;
		// }
		localCanvas.drawBitmap(paramBitmap, 0.0F, 0.0F, localPaint);
		localCanvas.drawText(paramString1, f, j - 85, localPaint);
		localCanvas.drawText(paramString2, f, j - 65, localPaint);
		localCanvas.drawText(paramString3, f, j - 45, localPaint);
		localCanvas.drawText(paramString4, f, j - 25, localPaint);
		localCanvas.save(31);
		localCanvas.restore();
		return localBitmap;
	}

	/**
	 * Download image from url.
	 */
	public static Bitmap loadImageFromUrl(String url) throws Exception {
		final DefaultHttpClient client = new DefaultHttpClient();
		final HttpGet getRequest = new HttpGet(url);

		HttpResponse response = client.execute(getRequest);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != HttpStatus.SC_OK) {
			LogUtils.e("PicShow", "Request URL failed, error code =" + statusCode);
		}

		HttpEntity entity = response.getEntity();
		if (entity == null) {
			LogUtils.e("PicShow", "HttpEntity is null");
		}
		InputStream is = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			is = entity.getContent();
			byte[] buf = new byte[1024];
			int readBytes = -1;
			while ((readBytes = is.read(buf)) != -1) {
				baos.write(buf, 0, readBytes);
			}
		} finally {
			if (baos != null) {
				baos.close();
			}
			if (is != null) {
				is.close();
			}
		}
		byte[] imageArray = baos.toByteArray();
		return BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length);
	}

	private static int width = 128;
	private static int height = 160;
	private static final String TAG = "ThumbnailCreator";

	/**
	 * 创建缩略图
	 * 
	 * @param imageSrc
	 * @return 返回null,如果这时无法获得缩略图
	 */
	public static Bitmap createThumbnail(Context context, String imageSrc) {
		boolean isJPG = false;
		Bitmap thumbnail = null;
		try {
			String ext = imageSrc.substring(imageSrc.lastIndexOf(".") + 1);
			if (ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg")) {
				isJPG = true;
			}
		} catch (IndexOutOfBoundsException e) {
			e.printStackTrace();
			return null;
		}

		if (isJPG) {
			try {
				ExifInterface mExif = null;
				mExif = new ExifInterface(imageSrc);
				if (mExif != null) {
					byte[] thumbData = mExif.getThumbnail();
					if (thumbData == null) {
						thumbnail = createThumbnailByOptions(context, imageSrc);
					} else {
						thumbnail = BitmapFactory.decodeByteArray(thumbData, 0,
								thumbData.length);
					}
				} else {
					thumbnail = createThumbnailByOptions(context, imageSrc);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		} else {
			thumbnail = createThumbnailByOptions(context, imageSrc);
		}
		return thumbnail;
	}

	private static Bitmap createThumbnailByOptions(Context context,
			String imageSrc) {
		Bitmap thumb = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// thumb = BitmapFactory.decodeFile(imageSrc, options);
		thumb = getPic(context, imageSrc);
		if(thumb == null)
			return null;
//		int be = (int) (Math.min(options.outWidth / width, options.outHeight
//				/ height));
//		if (be <= 0)
//			be = 1;
//		options.inSampleSize = be;
//		options.inJustDecodeBounds = false;
//		// thumb = BitmapFactory.decodeFile(imageSrc, options);
//		thumb = getPic(context, imageSrc, options);
//		if (thumb == null) {
//			/* 当不可decode时返回null */
//			return null;
//		}
		thumb = ThumbnailUtils.extractThumbnail(thumb, width, height);
//		thumb = Bitmap.createScaledBitmap(thumb, width, height, false);
		return thumb;
	}

	// }

	public static byte[] decodeBitmap(String path) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;// 设置成了true,不占用内存，只获取bitmap宽高
		BitmapFactory.decodeFile(path, opts);
		opts.inSampleSize = computeSampleSize(opts, -1, 1024 * 800);
		opts.inJustDecodeBounds = false;// 这里一定要将其设置回false，因为之前我们将其设置成了true
		opts.inPurgeable = true;
		opts.inInputShareable = true;
		opts.inDither = false;
		opts.inPurgeable = true;
		opts.inTempStorage = new byte[16 * 1024];
		FileInputStream is = null;
		Bitmap bmp = null;
		ByteArrayOutputStream baos = null;
		try {
			is = new FileInputStream(path);
			bmp = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts);
			double scale = getScaling(opts.outWidth * opts.outHeight,
					1024 * 600);
			Bitmap bmp2 = Bitmap.createScaledBitmap(bmp,
					(int) (opts.outWidth * scale),
					(int) (opts.outHeight * scale), true);
			baos = new ByteArrayOutputStream();
			bmp2.compress(Bitmap.CompressFormat.JPEG, 90, baos);
			bmp2.recycle();
			bmp.recycle();
			return baos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(is != null)
					is.close();
				if(baos != null)
					baos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.gc();
		}
		if(baos == null)
			return null;
		return baos.toByteArray();
	}

	private static double getScaling(int src, int des) {
		/**
		 * 48 目标尺寸÷原尺寸 sqrt开方，得出宽高百分比 49
		 */
		double scale = Math.sqrt((double) des / (double) src);
		return scale;
	}

	public static int computeSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength,
				maxNumOfPixels);

		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}

		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
				.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
				Math.floor(w / minSideLength), Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}


}
